function string_to_float(s) {
	if (s) 
		return parseFloat(s);
	else
		return 0.0;
};


function sum_inline(self, inline, field,start){
	if ( start == undefined ) start = 0;
	total = start;
	//$("#" + inline + "-group > ." + field).each(function() {
	$("." + field).each(function() {
		total += string_to_float($(this).children().val());
	});
	return total;
};

function safe(value, default_value){
	if (value)
		return value;
	else
		return default_value;
};
	
function sum_values(iter, start){
	if ( start == undefined ) start = 0;
	total = start;
	for (i in iter) {
		if (i) {
			total += iter[i];
		};
	};
	return total;
};

function fill_values(){
	self = {}

	{% for field in gets %}
		{% for field2 in field.2 %}
			self.{{field2}}  = string_to_float($("#id_{{field2}}").val());
		{% endfor %}
	{% endfor %}
	try {
	  	custom_fill_values();
    }catch(err){
    };
	
};



function bind_items() {
	try {
	  	custom_bind_items();
    }catch(err){
    };
	t = 0;
	{% for field in gets %}
		{% for field2 in field.2 %}
			$("#id_{{field2}}").change(calc_{{field.0}});
		{% endfor %}
	{% endfor %}
	{% for inline in inlines %}
		$("#id_{{inline}}-TOTAL_FORMS").change(bind_items);
	{% endfor %}
};


{% for get in gets %}
function  get_{{get.0}} () {
	{% for line in get.1 %}
		{{line|safe}};
	{% endfor %}
};

function calc_{{get.0}} (){
	fill_values();
	$("#id_{{get.0}}").val(get_{{get.0}}());
	$("#id_{{get.0}}").change();
};
{% endfor %}


function get_item_inline(elem) {
	id = $(elem).attr('id');
	var re = new RegExp("id_[a-z]+-([0-9]+)-[a-z]+");
	var m = re.exec (id);
	return m[1];
};

$(function () { 
	$(".add-row td a").click(bind_items);
	bind_items();
});
